//
// Created by Administrator on 2020/11/29.
//

#include "JavaCallHelper.h"
#include "macro.h"

JavaCallHelper::JavaCallHelper(JavaVM *pVm, JNIEnv *pEnv, jobject pJobject) {
    this->vm = pVm;
    this->env = pEnv;
    this->jobject1 = pEnv->NewGlobalRef(pJobject);
    jclass clazz = pEnv->GetObjectClass(pJobject);
    onErrorId = pEnv->GetMethodID(clazz, "onError", "(I)V");
    onPrepareId = pEnv->GetMethodID(clazz, "onPrepare", "()V");
}

JavaCallHelper::~JavaCallHelper() {
    env->DeleteGlobalRef(jobject1);
}

void JavaCallHelper::onError(int thread, int errorCode) {
    if (thread == THREAD_MAIN) {
    env->CallVoidMethod(jobject1,onErrorId,errorCode);
    } else {
        JNIEnv* threadEnv=0;
        vm->AttachCurrentThread(&threadEnv,0);
        threadEnv->CallVoidMethod(jobject1,onErrorId,errorCode);
        vm->DetachCurrentThread();
    }
}

void JavaCallHelper::onPrepare(int thread) {
    if (thread == THREAD_MAIN) {
        env->CallVoidMethod(jobject1,onPrepareId);
    } else {
        JNIEnv* threadEnv=0;
        vm->AttachCurrentThread(&threadEnv,0);
        threadEnv->CallVoidMethod(jobject1,onPrepareId);
        vm->DetachCurrentThread();
    }
}
